import terminal from "@/mount/global/misson/terminal"
import { GenerateAbility, isInArray } from "@/utils"
import { resourceMap } from "./constant"

export default class ActionMissonExtension extends Room {
    /* 底层合成任务 */
    public Task_Com(misson:MissionModel):void{
        if (Game.time % 5) return
        if (!this.memory.StructureIdData.labInspect || Object.keys(this.memory.StructureIdData.labInspect).length < 3) return
        if (!this.memory.StructureIdData.storageID)return
        var storage_ = Game.getObjectById(this.memory.StructureIdData.storageID) as StructureStorage
        if (!storage_) return
        var raw1 = Game.getObjectById(this.memory.StructureIdData.labInspect.raw1) as StructureLab
        var raw2 = Game.getObjectById(this.memory.StructureIdData.labInspect.raw2) as StructureLab
        if (misson.data.num <= 0)
        {
            this.DeleteMisson(misson.id)
            return
        }
        var re = false
        for (var i of misson.data.comData?misson.data.comData:this.memory.StructureIdData.labInspect.com)
        {
            var thisLab = Game.getObjectById(i) as StructureLab
            if (!thisLab) continue
            if (thisLab.cooldown) continue
            /* 计算有无被强化 */
            let comNum = 5
            if (thisLab.effects && thisLab.effects.length > 0)
            {
                for (var effect_ of thisLab.effects)
                {
                    if (effect_.effect == PWR_OPERATE_LAB)
                    {
                        var level = effect_.level
                        comNum += level*2
                    }
                }
            }
            if (thisLab.runReaction(raw1,raw2) == OK) {misson.data.num -= comNum}
            if (thisLab.store.getUsedCapacity(thisLab.mineralType) >= 2500 && this.RoleMissonNum('transport','物流运输') < 1)
            {
                /* 资源快满了就要搬运 */
                re = true
                var thisTask = this.Public_Carry({'transport':{num:1,bind:[]}},30,this.name,thisLab.pos.x,thisLab.pos.y,this.name,storage_.pos.x,storage_.pos.y,thisLab.mineralType,thisLab.store.getUsedCapacity(thisLab.mineralType))
                this.AddMisson(thisTask)
                continue
            }
        }
        if (re) return
        /* 源lab缺资源就运 */
        if (raw1.store.getUsedCapacity(misson.data.raw1) < 500)
        {
            var thisTask = this.Public_Carry({'transport':{num:1,bind:[]}},30,this.name,storage_.pos.x,storage_.pos.y,this.name,raw1.pos.x,raw1.pos.y,misson.data.raw1,1000)
            this.AddMisson(thisTask)
        }
        if (raw2.store.getUsedCapacity(misson.data.raw2) < 500)
        {
            var thisTask = this.Public_Carry({'transport':{num:1,bind:[]}},30,this.name,storage_.pos.x,storage_.pos.y,this.name,raw2.pos.x,raw2.pos.y,misson.data.raw2,1000)
            this.AddMisson(thisTask)
        }
        /* storage 缺资源就买、传 */
        var needResource:ResourceConstant[] = [misson.data.raw1,misson.data.raw2]
        var terminal_ = Game.getObjectById(this.memory.StructureIdData.terminalID) as StructureTerminal
        if (!terminal_) return
        for (var resource_ of needResource)
        {
            // 原矿 优先调用，如果调用失败就购买
            if(storage_.store.getUsedCapacity(resource_) + terminal_.store.getUsedCapacity(resource_) < 10000 && isInArray(['H','O','K','L','X','U','Z'],resource_))
            {
                if (!this.Resource_Dispatch(resource_,10000))
                    this.Deal_Resource(resource_,10000,5,10)
                return
            }
            // 其他中间资源,如果其他房间有的话从其他房间调，没有的话购买
            else if (storage_.store.getUsedCapacity(resource_)+ terminal_.store.getUsedCapacity(resource_) <  500 && !isInArray(['H','O','K','L','X','U','Z'],resource_))
            {
                if (!this.Resource_Dispatch(resource_,600))
                {
                    this.Deal_Resource(resource_,600,20,80)
                }
                return
            }
        }
    }

    /* 资源合成调度  */
    public Task_ComDispatch():void{
        if (Game.time % 50)return
        if (!this.memory.ComDispatchData) this.memory.ComDispatchData = []
        if (this.memory.ComDispatchData.length <= 0)return
        if (this.MissonNum('Room','资源合成') > 0) return
        if (!this.memory.StructureIdData.storageID || !this.memory.StructureIdData.terminalID)return
        var storage_ = global.Stru[this.name]['storage'] as StructureStorage
        if (!storage_) return
        var terminal_ = global.Stru[this.name]['terminal'] as StructureTerminal
        if (!terminal_) return
        /* 没有房间合成实验室数据，不进行合成 */
        if (!this.memory.StructureIdData.labInspect.raw1){console.log(`房间${this.name}不存在合成实验室数据！`);return}
        /* 查看合成实验室的被占用状态 */
        if (this.memory.RoomLabBind[this.memory.StructureIdData.labInspect.raw1] || this.memory.RoomLabBind[this.memory.StructureIdData.labInspect.raw2])
        {console.log(`房间${this.name}的源lab被占用！`);return}
        var comLabs = []
        for (var otLab of this.memory.StructureIdData.labInspect.com)
        {
            if (!this.memory.RoomLabBind[otLab]) comLabs.push(otLab)
        }
        if (comLabs.length <=0) {console.log(`房间${this.name}的合成lab全被占用！`);return}
        /* 确认所有目标lab里都没有其他资源 */
        for (var i of this.memory.StructureIdData.labs)
        {
            var thisLab = Game.getObjectById(i) as StructureLab
            if (!thisLab) continue
            if (thisLab.mineralType && !this.memory.RoomLabBind[i]) return
        }
        /* 正式下达合成任务 */
        Loopc:
        for (var disType of this.memory.ComDispatchData)
        {
            if (storage_.store.getUsedCapacity(disType.res) < disType.dispatch_num + 3000 && disType.num <= 0)
            {
                /* 先判定一下是否已经覆盖，如果已经覆盖就不合成 例如：ZK 和 G的关系，只要G数量满足了就不考虑 */
                var mapResource = resourceMap(disType.res,this.memory.ComDispatchData[this.memory.ComDispatchData.length-1].res)
                if (mapResource.length > 0)
                {
                    for (var mR of mapResource)
                    {
                        if (storage_.store.getUsedCapacity(mR) >= disType.dispatch_num + 2000)
                            continue Loopc
                    }
                }
                /* 说明资源被转走了 */
                var thisTask = this.Public_Com(disType.dispatch_num- storage_.store.getUsedCapacity(disType.res) + 3000,disType.res,comLabs)
                this.AddMisson(thisTask)
                return
            }
            if (disType.num > 0)
            {
                /* 没合过的资源 */
                if (disType.res != this.memory.ComDispatchData[this.memory.ComDispatchData.length-1].res&&storage_.store.getUsedCapacity(disType.res) >= disType.dispatch_num + 3000)
                {
                    disType.num = 0
                    continue Loopc
                }
                if (!isInArray(['XGH2O','XGHO2','XLH2O','XLHO2','XUH2O','XUHO2','XKH2O','XKHO2','XZH2O','XZHO2'],disType.res))
                {
                    var mapResource = resourceMap(disType.res,this.memory.ComDispatchData[this.memory.ComDispatchData.length-1].res)
                    if (mapResource.length > 0)
                    {
                        for (var mR of mapResource)
                        {
                            if (storage_.store.getUsedCapacity(mR) >= disType.dispatch_num + 3000)
                            {
                                disType.num = 0
                                continue Loopc
                            }
                        }
                    }
                    
                    /* 如果可以进行资源调度，就尽量调度 有问题 */
                    if (disType.dispatch_num + 3000-storage_.store.getUsedCapacity(disType.res) > 0)
                    if (this.Resource_Dispatch(disType.res,disType.dispatch_num + 3000-storage_.store.getUsedCapacity(disType.res))  && storage_.store.getUsedCapacity(disType.res) + terminal_.store.getUsedCapacity(disType.res) >= disType.dispatch_num+3000)
                    {
                        console.log(this.name,'启用lab合成资源调度中：rType:',disType.res,' 数量：',disType.dispatch_num + 3000-storage_.store.getUsedCapacity(disType.res)) 
                        return
                    }
                }

                var thisTask = this.Public_Com(disType.res != this.memory.ComDispatchData[this.memory.ComDispatchData.length-1].res? disType.dispatch_num- storage_.store.getUsedCapacity(disType.res) + 3000:disType.dispatch_num+3000,disType.res,comLabs)
                if (this.AddMisson(thisTask))
                {
                    disType.num = 0
                    if (disType.res == this.memory.ComDispatchData[this.memory.ComDispatchData.length-1].res)
                    {
                        this.memory.ComDispatchData = []
                    }
                }
            }
        }
        /* 相关合成资源都处理了就自动解除合成调度计划 */
        for (var disType of this.memory.ComDispatchData)
        {
            if (disType.num > 0) return
        }
        this.memory.ComDispatchData = []
    }

    /* 资源合成高级自动化调度  (调用资源合成调度)待写 */


    /* 冲级任务 进行修改，不允许boost  新增逻辑允许没有boost进行刷级*/
    public Task_RushLevel(misson:MissionModel):void{
        if (Game.time % 3) return
        if (!this.memory.StructureIdData.upgrade_link || !this.memory.StructureIdData.center_link)return
        var storage_ = global.Stru[this.name]['storage'] as StructureStorage
        var center_link = Game.getObjectById(this.memory.StructureIdData.center_link) as StructureLink
        var upgrade_link = Game.getObjectById(this.memory.StructureIdData.upgrade_link) as StructureLink
        if (!storage_) {return}
        if (!center_link) {delete this.memory.StructureIdData.center_link;return}
        if (!upgrade_link){delete this.memory.StructureIdData.upgrade_link;return}
        if (storage_.store.getUsedCapacity('energy') < 20000) return    // 能量过少则不支持冲级
        /* 开始冲级任务流程 */
        // 爬虫孵化控制
        if (!misson.data.Nolab) misson.data.Nolab = false
        global.CreepNumData[this.name]['level'].num = misson.data.num
        // Link传送控制
        if (upgrade_link.store.getUsedCapacity('energy') < 500)
        {
                if (center_link.store.getUsedCapacity('energy') >= 400)
                {
                    var linkTask = this.Public_Link([center_link.id],upgrade_link.id,4)
                    this.AddMisson(linkTask)
                }
                else
                {
                    if (this.RoleMissonNum('manage','物流运输') <= 0)
                    {
                        var carryTask = this.Public_Carry({'manage':{num:1,bind:[]}},15,this.name,storage_.pos.x,storage_.pos.y,this.name,center_link.pos.x,center_link.pos.y,'energy',800)
                        this.AddMisson(carryTask)
                        return
                    }
                    if (this.RoleMissonNum('transport','物流运输') <= 0)
                    {
                        var carryTask = this.Public_Carry({'transport':{num:1,bind:[]}},15,this.name,storage_.pos.x,storage_.pos.y,this.name,center_link.pos.x,center_link.pos.y,'energy',800)
                        this.AddMisson(carryTask)
                        return
                    }
                }
            
        }
        // lab货运控制
        if (storage_.store.getUsedCapacity(misson.data.rType) >= 2000)
        misson.data.boosted = true
        else misson.data.boosted = false
        if (!misson.data.Nolab)
        {
            // 无论是否boosted，都会占用一个lab
            if (misson.data.boosted)
            {
            var disLab = Game.getObjectById(Object.keys(misson.LabBind)[0])  as StructureLab
            if (disLab.store.getUsedCapacity(misson.data.rType) < 500 && storage_.store.getUsedCapacity(misson.data.rType) >= 1000)
            {
                var carryTask = this.Public_Carry({'transport':{num:1,bind:[]}},25,this.name,storage_.pos.x,storage_.pos.y,this.name,disLab.pos.x,disLab.pos.y,misson.data.rType,2000)
                this.AddMisson(carryTask)
            }
            }
        }
        
    }

    /* 签名任务 */
    public Task_Sign(misson:MissionModel):void{
        if (Game.time % 39) return
        if (!misson.data.state) misson.data.state = 1
        if (misson.data.state == 1)
        {
            global.CreepNumData[this.name]['scout'].num += misson.CreepBind['scout'].num
            if (misson.CreepBind['scout'].num == misson.CreepBind['scout'].bind.length) misson.data.state =2
        }  
    }

    /* boost援建一体机任务 */
    public Task_BoostHelpBuild(misson:MissionModel):void{
        if (Game.time % 15) return
        if (!misson.data.state) misson.data.state = 1
        if (!this.memory.StructureIdData.storageID )return
        var storage_ = Game.getObjectById(this.memory.StructureIdData.storageID) as StructureStorage
        if (!storage_) return
        if (!this.Check_Lab(misson,'transport','storage')) return
        if (misson.data.state == 1)
        {
            misson.data.state = 2
        }
        else if (misson.data.state == 2)
        {
            global.CreepNumData[this.name]['claim'].num += misson.CreepBind['claim'].num
            global.CreepNumData[this.name]['architect'].num += misson.CreepBind['architect'].num
            if (misson.CreepBind['claim'].num == misson.CreepBind['claim'].bind.length && misson.CreepBind['architect'].num == misson.CreepBind['architect'].bind.length)
            misson.data.state = 3
        }
        else
        {
            console.log("任务进入休眠模式")
        }
    }

    /* 冲级协助任务 */
    public Task_HelpUpgrade(misson:MissionModel):void{
        if (Game.time % 10) return
        if (!misson.data.state) misson.data.state = 1
        if (!this.Check_Lab(misson,'transport','complex')) return
        if (misson.data.state == 1)
        {
            if (!misson.data.startTime)misson.data.startTime = Game.time
            global.CreepNumData[this.name]['upgrade-help'].num += misson.CreepBind['upgrade-help'].num
            if (misson.data.shard != Game.shard.name && misson.CreepBind['upgrade-help'].num == misson.CreepBind['upgrade-help'].bind.length)
            {
                misson.data.state = 2
            }
        }
        else if (misson.data.state == 2)
        {
            misson.CreepBind['upgrade-help'].num = 0
            if ((Game.time - misson.data.startTime) % 1100 == 0)
            {
                misson.CreepBind['upgrade-help'].num = misson.data.build_help_num
                misson.data.state = 1
            }
        }
        
    }

    /* 后勤协助任务 */
    public Task_HelpRear(misson:MissionModel):void{
        if (Game.time % 10) return
        if (!misson.data.state) misson.data.state = 1
        if (!misson.data.startTime)misson.data.startTime = Game.time
        var storage_ = global.Stru[this.name]['storage'] as StructureStorage
        if (!storage_) return
        if (!this.Check_Lab(misson,'transport','storage')) return
        /* 先负责lab的填充 */
        if (misson.data.state == 1)
        {
            global.CreepNumData[this.name]['rear-help'].num += misson.CreepBind['rear-help'].num
            if (misson.data.shard != Game.shard.name && misson.CreepBind['rear-help'].num == misson.CreepBind['rear-help'].bind.length)
            {
                misson.data.state = 2
            }
        }
        else if (misson.data.state == 2)
        {
            misson.CreepBind['rear-help'].num = 0
            if ((Game.time - misson.data.startTime) % (misson.data.time?misson.data.time:1000) == 0)
            {
                misson.CreepBind['rear-help'].num = misson.data.build_help_num
                misson.data.state = 1
            }
        }
    }

    /* 刷墙任务 */
    public Task_Repair(misson:MissionModel):void{
        if (!misson.data.startTime)misson.data.startTime = Game.time
        if ((Game.time - misson.data.startTime) % 10) return
        var storage_ = global.Stru[this.name]['storage'] as StructureStorage
        if (!storage_) return
        if (misson.data.vindicate)
        global.CreepNumData[this.name]['repair'].ability = GenerateAbility(10,10,10)
        global.CreepNumData[this.name]['repair'].num += misson.CreepBind['repair'].num
        if (misson.LabBind)
            if (!this.Check_Lab(misson,'transport','complex')) return
        
    }
}